import AuthApi from '../api/auth.js';

/**
 * 登录工具类
 */
class LoginUtils {
  /**
   * 检查并处理用户登录状态
   * 如果用户未登录，则尝试微信静默登录
   */
  static async checkAndHandleLogin() {
    let openId = uni.getStorageSync('openId');
    // openId = 'oVV5LvuwpXOXOh3DPT_wzu2LPL7U';
 
    // 在执行所有登录方式之前先获取渠道
    let provider = await this.initProvider();

    console.log("当前openId: ", openId);
    
    if (openId === "" || !openId) {
      console.log("openId不存在，开始code登录流程");
      await this.performCodeLogin();
    } else {
      console.log('缓存中已存在 openId:', openId);
      await this.refreshLoginWithOpenId(openId);
    }
  }
  
  /**
   * 使用openId刷新用户登录信息
   * @param {string} openId 微信openId
   */
  static async refreshLoginWithOpenId(openId) {
    try {
      let channel = uni.getStorageSync('channel');
      console.log('开始使用openId刷新登录信息:{} {}', openId,channel);
      
      const result = await AuthApi.otherOpenIdLogin(openId,channel);
      
      if (result && result.accessToken) {
        console.log(result)
        // 保存新的token信息
        uni.setStorageSync('memberId', result.memberId);
        uni.setStorageSync('token', result.accessToken);
        uni.setStorageSync('registerStatus', result.registerStatus);
        console.log('openId登录刷新成功');
      } else {
        console.warn('openId登录返回数据格式异常');
      }
    } catch (error) {
      console.error('openId登录刷新失败:', error);
      
      // 如果openId登录失败，清除openId并重新进行微信登录
      uni.removeStorageSync('openId');
      uni.removeStorageSync('token');
      uni.removeStorageSync('refreshToken');
      
      console.log('openId失效，重新进行code登录');
      await this.performCodeLogin();
    }
  }
  
  /**
   * 执行微信登录流程
   */
  static async performCodeLogin() {
    let optionsSync = uni.getLaunchOptionsSync();
    let query = optionsSync.query;
    let inviterId = null;
    console.log("页面参数", query);
    const scene = query ? decodeURIComponent(query.scene) : null;
    console.log("页面scene", scene);

    if (query && query.inviterId){
      inviterId = query.inviterId;
    }
    if (scene){
      // 解析scene参数，格式为key=value&key2=value2
      const sceneStr = String(scene);
      const pairs = sceneStr.split('&');
      
      for (const pair of pairs) {
        const [key, value] = pair.split('=');
        if (key === 'inviterId' && value) {
          inviterId = decodeURIComponent(value);
          console.log('从scene中获取到的inviterId:', inviterId);
          break;
        }
      }
      
      // 这里可以添加其他scene参数的处理逻辑
    }

    return new Promise((resolve, reject) => {
      // 使用已初始化的provider
      let provider = uni.getStorageSync('loginProvider');
      console.log("登录渠道",provider);
      this.doCodeLogin(resolve, reject, inviterId, provider);
    });
  }
  
  /**
   * 初始化登录服务提供商
   */
  static async initProvider() {
    let provider = uni.getStorageSync('loginProvider');
    let channel = uni.getStorageSync('channel');
    if (provider && channel) {
      return provider;
    }
    try{
      return new Promise((resolve, reject) => {
        uni.getProvider({
          service: 'oauth',
          success: (res) => {
            console.log('可用的登录服务:', res.provider);
            let provider = res.provider[0];
            // 缓存provider信息
            uni.setStorageSync('loginProvider', provider);
            uni.setStorageSync('channel', provider === "weixin" ? 1 : 0);
            resolve(provider);
          },
          fail: (err) => {
            console.error('获取登录服务失败:', err);
            reject(err);
          }
        });
      });
    }catch(err){
      console.error('初始化登录服务失败:', err);
      reject(err);
    }

  }

  /**
   * 执行微信登录
   */
  static doCodeLogin(resolve, reject, inviterId, provider) {
    uni.login({
      provider: provider,
      success: async (loginRes) => {
        console.log("获取" + provider + "小程序code成功:", JSON.stringify(loginRes));

        // 调用后端接口，使用 code 换取 openId
        let channel = this.getChannel();
        const result = await AuthApi.otherQuiesceLogin(loginRes.code,inviterId,channel);
        console.log(result)
        if (result) {
          const openId = result.openId;
          uni.setStorageSync('openId', openId);
          uni.setStorageSync('channel', channel);
          uni.setStorageSync('miniType', 1);
          uni.setStorageSync('memberId', result.memberId);
          uni.setStorageSync('token', result.accessToken);
          uni.setStorageSync('registerStatus', result.registerStatus)

          console.log('获取并缓存 openId 成功:', openId);
          resolve(openId);
        } else {
          throw new Error('服务器返回数据格式错误');
        }

      },
      fail: (err) => {
        console.error(provider + '授权失败:', err);
        uni.showToast({ 
          title: '授权失败', 
          icon: 'none' 
        });
        reject(err);
      }
    });
  }
  
  /**
   * 检查用户是否已登录
   * @returns {boolean} 是否已登录
   */
  static isLoggedIn() {
    const token = uni.getStorageSync('token');
    const openId = uni.getStorageSync('openId');
    return !!(token && openId);
  }
  static getLoginId() {
    const memberId = uni.getStorageSync('memberId');
    return memberId;
  }
  /**
   * 重定向到登录页面
   */
  static redirectToLogin() {
    // uni.showModal({
    //   title: '需要登录',
    //   content: '请先登录后再使用此功能',
    //   showCancel: false,
    //   success: () => {
    //     // 这里可以跳转到登录页面或执行登录流程
    //     this.checkAndHandleLogin();
    //   }
    // });
  }
  
  /**
   * 退出登录
   */
  static logout() {
    uni.removeStorageSync('token');
    uni.removeStorageSync('openId');
    uni.removeStorageSync('memberId');
    uni.removeStorageSync('refreshToken');
    uni.removeStorageSync('channel');
    uni.removeStorageSync('miniType');
    
    // 退出登录后刷新当前页面
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 2];
    const currentRoute = currentPage.route;
    const currentOptions = currentPage.options;
    
    // 构建页面路径和参数
    let url = '/' + currentRoute;
    const params = Object.keys(currentOptions).map(key => `${key}=${currentOptions[key]}`).join('&');
    if (params) {
      url += '?' + params;
    }

    this.performCodeLogin();


    uni.reLaunch({
      url: url
    });
  }

  static checkLoginStatus () {
    const registerStatus = uni.getStorageSync('registerStatus')
    console.log('registerStatus', registerStatus);
    return !registerStatus && registerStatus === 0
  }

  static checkStatusToLogin () {
    let status = this.checkLoginStatus();
    if (!status) {
      this.goToLogin()
      return false;
    }
    return status;
  }

  static goToLogin () {
    uni.navigateTo({
      url: '/pages/login/index'
    })
  }

  static getChannel(){
    let channel = uni.getStorageSync('channel');
    return channel === "0" || channel === 0 ? 0: 1;
  }

}

export default LoginUtils;
